package com.jiahao.quickshot;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.jiahao.quickshot.Service.ScreenShotsService;

import java.io.File;


public class MainActivity extends Activity implements View.OnClickListener{
    private String TAG = "MainActivity";
    private Bitmap LargeIcon = null;
    private NotificationManager mNManager;
    private Notification Notify;
    private Button snapper;
    private MediaProjectionManager mMediaProjectionManager;
    private Intent shotIntent = null;

    private int mResultCode;
    private Intent mResultData;
    private static final int NOTIFICATION_1 = 1;
    private int REQUEST_MEDIA_PROJECTION = 1;
    private static final String STATE_RESULT_CODE = "result_code";
    private static final String STATE_RESULT_DATA = "result_data";
    private static final int MY_PERMISSIONS_REQUEST_STORAGE = 1;
    private static final int SMALL_ICON_ID = R.mipmap.ic_launcher;
    private static final int LARGE_ICON_ID = R.drawable.ic_camera_black_36dp;
    /***
     * 4.4以下(也就是kitkat以下)的版本
     */
    public static final int KITKAT_LESS = 190;
    /***
     * 4.4以上(也就是kitkat以上)的版本,当然也包括最新出的5.0棒棒糖
     */
    public static final int KITKAT_ABOVE = 191;
    /**
     * 被选图片的uri
     */
    private static final String PIC_URI = "pic_uri";

    private FileObserver mFileObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) {
            mResultCode = savedInstanceState.getInt(STATE_RESULT_CODE);
            mResultData = savedInstanceState.getParcelable(STATE_RESULT_DATA);
        }
        LargeIcon = BitmapFactory.decodeResource(getResources(), LARGE_ICON_ID);
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        createScreenCaptureEnvironment();
        //获取SD卡读写权限
        if (Build.VERSION.SDK_INT >= 23) {
            permissionsCheck();
        }
        initView();
        mFileObserver = new ScreenShotsLister(Environment.getExternalStorageDirectory().getPath()+"/Pictures/ScreenShots");
        mFileObserver.startWatching(); //开始监听
    }

    private void initView(){
        snapper = (Button)findViewById(R.id.snapper);
        Button editor = (Button)findViewById(R.id.editor);
        snapper.setOnClickListener(this);
        editor.setOnClickListener(this);
    }

    /**
     * 权限检查与获取
     */
    private void permissionsCheck(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "Get Permissions");
            if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                showMessageOKCancel(getString(R.string.permission_notice),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_STORAGE);
                        }
                        });
                return;
            }
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_STORAGE);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mResultData != null) {
            Log.i(TAG, "onSaveInstanceState()");
            outState.putInt(STATE_RESULT_CODE, mResultCode);
            outState.putParcelable(STATE_RESULT_DATA, mResultData);
        }
    }

    private void createScreenCaptureEnvironment(){
        Log.i(TAG, "createScreenCaptureEnvironment()");
        mMediaProjectionManager = (MediaProjectionManager)getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    }

    private void startScreenCapture(){
        if(mResultData != null && mResultCode != 0){
            Log.i(TAG, "startScreenCapture(1)");
            ((ShotApplication)getApplication()).setResult(mResultCode);
            ((ShotApplication)getApplication()).setIntent(mResultData);
            onClickCustomNotification();
        }else{
            Log.i(TAG, "startScreenCapture(2)");
            startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
            ((ShotApplication)getApplication()).setMediaProjectionManager(mMediaProjectionManager);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.snapper:
//                createNotification();
                startScreenCapture();
                break;
            case R.id.editor:
                ImageHelper.getInstance().selectPicture(this);
                break;
        }
    }

    public void onClickCustomNotification(){
        Log.i(TAG, "createNotification");
        Notification.Builder builder = new Notification.Builder(this);
        //定义一个PendingIntent点击Notification返回Activity
        Intent i = new Intent(this, MainActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(this, 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setTicker("Custom Ticker")
                .setSmallIcon(SMALL_ICON_ID)
//                .setLargeIcon(LargeIcon)
                .setContentIntent(intent)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
                .setPriority(Notification.PRIORITY_DEFAULT)//设置优先级
                .setFullScreenIntent(intent, true);
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_layout_withbutton);
        builder.setContent(remoteViews);
        NotificationTextColorCompat.byAuto(this).setContentTitleColor(remoteViews, R.id.notification_content_title)
                .setContentTextColor(remoteViews, R.id.notification_content_text);
        remoteViews.setTextViewText(R.id.notification_content_title, getResources().getString(R.string.ContentTitle));
        remoteViews.setTextViewText(R.id.notification_content_text, getResources().getString(R.string.ContentText));
        remoteViews.setImageViewResource(R.id.notification_large_icon, LARGE_ICON_ID);
        //定义一个PendingIntent点击按钮触发截屏
        shotIntent = new Intent(this, ScreenShotsService.class);
        PendingIntent pIShot = PendingIntent.getService(this, 0, shotIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.notification_button, pIShot);
        Notify = builder.build();
        mNManager.notify(NOTIFICATION_1, Notify);
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("确定", okListener)
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data) {
            return;
        }
        //Start--截屏授权--
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode != Activity.RESULT_OK) {
                Log.i(TAG, "User cancelled");
                Snackbar.make(snapper, getResources().getString(R.string.user_cancelled), Snackbar.LENGTH_INDEFINITE)
                        .setAction("重新授权", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startScreenCapture();
                            }
                        })
                        .show();
//                Toast.makeText(this, R.string.user_cancelled, Toast.LENGTH_SHORT).show();
                return;
            }else {
                //发送截屏通知
                onClickCustomNotification();
            }
            mResultCode = resultCode;
            mResultData = data;
            ((ShotApplication) getApplication()).setResult(resultCode);
            ((ShotApplication) getApplication()).setIntent(data);
            return;
        }
        //End--截屏授权--
        //Start--图片选择--
        Uri uri;
        if (requestCode ==   KITKAT_LESS) {
            uri = data.getData();
            Log.d(TAG, "uri=" + uri);
            Intent i = new Intent(this, EditorActivity.class);
            i.putExtra(PIC_URI, uri);
            startActivity(i);
            // 调用裁剪方法
//            PicFactory.getInstance().cropPicture(this, uri);
        } else if (requestCode == KITKAT_ABOVE) {
            uri = data.getData();
            Log.d(TAG, "uri=" + uri);
            // 先将这个uri转换为path，然后再转换为uri
            String thePath = ImageHelper.getInstance().getPath(this, uri);
            Intent i = new Intent(this, EditorActivity.class);
            i.putExtra(PIC_URI, Uri.fromFile(new File(thePath)));
            startActivity(i);
                 /* PicFactory.getInstance().cropPicture(this,
                    Uri.fromFile(new File(thePath)));*/
        }
        //End--图片选择--
        /*else if (requestCode == AppConstant.INTENT_CROP) {
            Bitmap bitmap = data.getParcelableExtra("data");
            ivResult.setImageBitmap(bitmap);
            File temp = new File(Environment.getExternalStorageDirectory()
                    .getPath() + "/yourAppCacheFolder/");// 自已缓存文件夹
            if (!temp.exists()) {
                temp.mkdir();
            }
            File tempFile = new File(temp.getAbsolutePath()+"/"
                    + Calendar.getInstance().getTimeInMillis() + ".jpg"); // 以时间秒为文件名
            // 图像保存到文件中
            FileOutputStream foutput = null;
            try {
                foutput = new FileOutputStream(tempFile);
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, foutput)) {
                    Toast.makeText(MainActivity.this,
                            "已生成缓存文件，等待上传！文件位置：" + tempFile.getAbsolutePath(),
                            Toast.LENGTH_LONG).show();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }*/
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        if (requestCode == MY_PERMISSIONS_REQUEST_STORAGE)
        {
            if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Toast.makeText(MainActivity.this, getString(R.string.permission_warning), Toast.LENGTH_LONG).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != shotIntent) stopService(shotIntent);
        if(null != mFileObserver) mFileObserver.stopWatching(); //停止监听
        Log.i(TAG, "onDestroy()");
    }
}
